package likouJava;

import java.util.Random;



public class 数组中的第K个最大元素 {
    private static final Random random = new Random();
    public int findKthLargest(int[] nums, int k) {
        int left = 0, right = nums.length - 1;
        int target = k - 1;
        while (true){
            int pvIndex = partition(nums, left, right);
            if (pvIndex == target){
                return nums[pvIndex];
            } else if (pvIndex < target) {
                left = pvIndex + 1;
            }else {
                right = pvIndex - 1;
            }
        }
    }

    private int partition(int[] nums, int left, int right) {
        int pvIndex = left + random.nextInt(right - left + 1);
        swap(nums, pvIndex, right);
        int pivot = nums[right];
        int storeIndex = left;

        for (int i = left; i < right; i++) {
            if (nums[i] > pivot){
                swap(nums, storeIndex, i);
                storeIndex++;
            }
        }
        swap(nums, storeIndex, right);
        return storeIndex;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }


}
